#coding:utf-8
'''
@author:        laohu
@date:          2021.07.18
@brief:         用户管理Tab页
@note:          
'''

from Infrastructure.ConstValues import DEFAULT_PAGE_SIZE
from sqlalchemy.sql.functions import user
from UIComponents.PageNavigator import PageNavigator
from UserManageDao import UserManageDao
from typing import Optional
from PySide6.QtWidgets import QAbstractItemView, QCheckBox, QComboBox, QDialog, QDialogButtonBox, QHBoxLayout, QHeaderView, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget
from PySide6.QtCore import Qt
from uuid import uuid1
from math import ceil

class UserManageTab(QWidget):
    def __init__(self, parent: Optional[QWidget] = None, f: Qt.WindowFlags = Qt.SubWindow) -> None:
        super().__init__(parent=parent, f=f)
        self.vlayout = QVBoxLayout(self)
        self.cbxGroups = QComboBox()
        self.vlayout.addWidget(self.cbxGroups)
        self.userManageTable = QTableWidget()
        self.vlayout.addWidget(self.userManageTable)
        self.buttonAddUser = QPushButton("添加用户")
        self.vlayout.addWidget(self.buttonAddUser)
        self.pagenavigator = PageNavigator(3)
        self.vlayout.addWidget(self.pagenavigator)
        self.groupInited = False
        self.initGroup()
        self.buttonAddUser.clicked.connect(self.buttonAddUserClicked)
        self.pagenavigator.currentPageChanged.connect(self.updateUserManageTable)
        self.updateUserManageTable(1)

    def initGroup(self):
        groups = UserManageDao.get_groups()
        if self.groupInited is True:
            self.cbxGroups.currentIndexChanged.disconnect(self.cbxGroupsIndexChanged)
        self.cbxGroups.clear()
        self.cbxGroups.addItem('全部', None)
        for group in groups:
            self.cbxGroups.addItem(group["group"], group["group"])
        self.cbxGroups.currentIndexChanged.connect(self.updateUserManageTable)
        self.groupInited = True


    # 更新userTable及分页控件
    def updateUserManageTable(self, pageIndex):
        self.userManageTable.clear()
        self.userManageTable.setRowCount(0)
        group = self.cbxGroups.currentData()
        if group is None:
            result = UserManageDao.search_user_page(True, pageIndex, DEFAULT_PAGE_SIZE)
        else:
            result = UserManageDao.search_user_page(True, pageIndex, DEFAULT_PAGE_SIZE, group = group)
        count = result[0]
        users = result[1]
        self.userManageTable.horizontalHeader().setFixedHeight(49)  ##设置表头高度
        self.userManageTable.setSelectionMode(QAbstractItemView.ExtendedSelection)  # 设置只可以单选，可以使用ExtendedSelection进行多选
        self.userManageTable.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置 不可选择单个单元格，只可选择一行。
        self.userManageTable.setColumnCount(4)  ##设置表格列数
        self.userManageTable.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.userManageTable.setHorizontalHeaderLabels(
            ['选择','姓名', '部门', '位置'])  # 设置表头文字
        row = self.userManageTable.rowCount()
        for item in users:
            self.userManageTable.insertRow(row)
            ##下面六行用于生成居中的checkbox，不知道有没有别的好方法
            ck = QCheckBox()
            h = QHBoxLayout()
            h.setAlignment(Qt.AlignCenter)
            h.addWidget(ck)
            w = QWidget()
            w.setLayout(h)
            self.userManageTable.setCellWidget(row, 0, w)
            self.userManageTable.setItem(row, 1, QTableWidgetItem(item.name))
            self.userManageTable.setItem(row, 2, QTableWidgetItem(item.group))
            self.userManageTable.setItem(row, 3, QTableWidgetItem(item.location))
            row +=0
        self.pagenavigator.setMaxPage(ceil(count * 1.0 / DEFAULT_PAGE_SIZE))
        self.pagenavigator.setCurrentPage(pageIndex)

    # 部门选择框变动响应
    def cbxGroupsIndexChanged(self):
        self.updateUserManageTable()

    # 添加用户响应
    def buttonAddUserClicked(self):
        dialogAddUser = QDialog(self)
        dialogAddUser.setWindowTitle("添加用户")
        dialogAddUser.resize(300, 100)
        vlayout = QVBoxLayout(dialogAddUser)
        lineEditName = QLineEdit(dialogAddUser)
        lineEditName.setPlaceholderText("姓名")
        vlayout.addWidget(lineEditName)
        lineEditGroup = QLineEdit(dialogAddUser)
        lineEditGroup.setPlaceholderText("部门")
        vlayout.addWidget(lineEditGroup)
        lineEditLocation = QLineEdit(dialogAddUser)
        lineEditLocation.setPlaceholderText("位置")
        vlayout.addWidget(lineEditLocation)
        buttons = QDialogButtonBox()
        buttons.addButton("确认", QDialogButtonBox.AcceptRole)
        buttons.addButton("取消", QDialogButtonBox.RejectRole)
        buttons.accepted.connect(dialogAddUser.accept)
        buttons.rejected.connect(dialogAddUser.reject)
        vlayout.addWidget(buttons)
        result = dialogAddUser.exec()
        if result is 1:
            user = {
                "uuid": str(uuid1()),
                "name": lineEditName.text(),
                "group": lineEditGroup.text(),
                "location": lineEditLocation.text()}
            UserManageDao.add_user(**user)
            self.userManageTable.insertRow(0)
            self.initGroup()
            self.updateUserManageTable(1)